import base64
import hmac
import json
import os
import time
from hashlib import sha1

import requests
from qcloud_cos import CosConfig
from qcloud_cos import CosS3Client
from qcloud_cos.cos_auth import CosS3Auth

secret_id = 'AKIDyyFnIm7NYzLdq1ACINNBCNRQKDB3t6Xz'  # 用户的 SecretId，建议使用子账号密钥，授权遵循最小权限指引，降低使用风险。子账号密钥获取可参见 https://cloud.tencent.com/document/product/598/37140
secret_key = 'lxHgE7ydAoOrPSWes7LUbp3JXj5d9bu8'  # 用户的 SecretKey，建议使用子账号密钥，授权遵循最小权限指引，降低使用风险。子账号密钥获取可参见 https://cloud.tencent.com/document/product/598/37140
bucket_name = 'context-1257245862'
# 设置 bucket 名称和存储区域
region = 'ap-chengdu'
aa = 'https://context-1257245862.cos.ap-chengdu.myqcloud.com'
config = CosConfig(Region=region, SecretId=secret_id, SecretKey=secret_key)
client = CosS3Client(config)
token = None

# 定义要上传的文件名
key = 'path/to/file.jpg'

# 定义过期时间
expire = int(time.time()) + 3600  # 过期时间为 1 小时后

# 构建 POST 策略
policy = {
    "expiration": str(expire),
    "conditions": [
        {"bucket": bucket_name},
        ["starts-with", "$key", ""],
        {"success_action_status": "200"},
        ["eq", "$Content-Type", "image/jpeg"],
        ["content-length-range", 0, 10485760]
    ]
}

# 将策略转换为 base64 编码的字符串
policy_base64 = base64.b64encode(json.dumps(policy).encode()).decode()

# 使用 HMAC-SHA1 计算签名
signature = base64.encodebytes(
    hmac.new(secret_key.encode(), policy_base64.encode(), sha1).digest()
).strip().decode()

# 构建最终的表单数据
form_data = {
    "key": key,
    "policy": policy_base64,
    "signature": signature,
    "x-cos-meta-fileid": "fileid",
    "x-cos-meta-filename": "filename",
    "success_action_status": "200",
    "Content-Type": "image/jpeg"
}

print("Form Data:", form_data)